﻿using NCS.IConnect.Core.Utilities;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace NCS.IConnect.Core.WebApi.Description
{
    internal static class Extensions
    {
        public static string ToCamelCase(this string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return value;
            }
            return value.Substring(0, 1).ToLower() + (value.Length == 1 ? "" : value.Substring(1));
        }

        public static object GetDefaultValue(this PropertyInfo parameter)
        {
            DefaultValueAttribute attribute = parameter.GetCustomAttributes<DefaultValueAttribute>().FirstOrDefault();
            if (null == attribute)
            {
                return null;
            }
            return attribute.Value;
        }

        public static string ToJson(this object value)
        {
            var jsonFormatter = new JsonMediaTypeFormatter();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            using (MemoryStream stream = new MemoryStream())
            {
                jsonFormatter.WriteToStream(value.GetType(), value, stream, Encoding.UTF8);
                stream.Position = 0;
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        public static string GetReasonPhrase(this HttpStatusCode statusCode)
        {
            Func<char, bool> isUpperCase = c => c >= 'A' && c <= 'Z';

            string reasonPhrase = statusCode.ToString();
            List<int> indexList = new List<int>();
            for (int i = 1; i < reasonPhrase.Length; i++)
            {
                if (isUpperCase(reasonPhrase[i]) && !isUpperCase(reasonPhrase[i-1]))
                {
                    indexList.Add(i);
                }
            }
            indexList.Add(reasonPhrase.Length);
            string result = "";
            int start = 0;
            foreach (int index in indexList)
            {
                if (index == start + 1)
                {
                    result += reasonPhrase[index];
                }
                else
                {
                    result += reasonPhrase.Substring(start, index - start) + " ";
                }
                start = index;
            }
            return result.TrimEnd();
        }
    }
}
